home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 117 / PC Guia 117.iso / Software / Produtividade / Software2 / Product4 / Setup.exe / drupal-4.6.0 / modules / search.module < prev    next >
Encoding:
Text File  |  2005-04-12  |  30.8 KB  |  858 lines

  1. <?php
  2. // $Id: search.module,v 1.123.2.1 2005/04/11 22:50:41 unconed Exp $
  3.  
  4. /**
  5.  * @file
  6.  * Enables site-wide keyword searching.
  7.  */
  8.  
  9. /**
  10.  * Matches Unicode character classes to exclude from the search index.
  11.  *
  12.  * See: http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values
  13.  *
  14.  * The index only contains the following character classes:
  15.  * Lu     Letter, Uppercase
  16.  * Ll     Letter, Lowercase
  17.  * Lt     Letter, Titlecase
  18.  * Lm     Letter, Modifier
  19.  * Lo     Letter, Other
  20.  * Mn     Mark, Nonspacing
  21.  * Mc     Mark, Spacing Combining
  22.  * Nd     Number, Decimal Digit
  23.  * Nl     Number, Letter
  24.  * No     Number, Other
  25.  * Sm     Symbol, Math
  26.  * Sc     Symbol, Currency
  27.  * Sk     Symbol, Modifier
  28.  * So     Symbol, Other
  29.  *
  30.  * All character classes not in the list above (enclosing marks, punctuation, control codes and spacers):
  31.  * 'Me', 'Pc', 'Pd', 'Ps', 'Pe', 'Pi', 'Pf', 'Po', 'Zs', 'Zl', 'Zp', 'Cc', 'Cf', 'Cs', 'Co'
  32.  */
  33. define('PREG_CLASS_SEARCH_EXCLUDE', '\x{0}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}\x{5f}\x{7b}\x{7d}\x{7f}-\x{a1}\x{ab}\x{ad}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{488}\x{489}\x{55a}-\x{55f}\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{600}-\x{603}\x{60c}\x{60d}\x{61b}\x{61f}\x{66a}-\x{66d}\x{6d4}\x{6dd}\x{6de}\x{700}-\x{70d}\x{70f}\x{964}\x{965}\x{970}\x{df4}\x{e4f}\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}\x{1361}-\x{1368}\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}\x{1736}\x{17b4}\x{17b5}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{180e}\x{1944}\x{1945}\x{2000}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}\x{205f}-\x{2063}\x{206a}-\x{206f}\x{207d}\x{207e}\x{208d}\x{208e}\x{20dd}-\x{20e0}\x{20e2}-\x{20e4}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}\x{3000}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}\x{30fb}\x{d800}\x{db7f}\x{db80}\x{dbff}\x{dc00}\x{dfff}\x{e000}\x{f8ff}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}\x{fe6a}\x{fe6b}\x{feff}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-\x{ff65}\x{fff9}-\x{fffb}\x{10100}\x{10101}\x{1039f}\x{1d173}-\x{1d17a}\x{e0001}\x{e0020}-\x{e007f}\x{f0000}\x{ffffd}\x{100000}');
  34.  
  35. /**
  36.  * Matches all 'N' Unicode character classes (numbers)
  37.  */
  38. define('PREG_CLASS_NUMBERS', '\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}\x{10107}-\x{10133}\x{10320}-\x{10323}\x{1034a}\x{104a0}-\x{104a9}\x{1d7ce}-\x{1d7ff}');
  39.  
  40. /**
  41.  * Matches all 'P' Unicode character classes (punctuation)
  42.  */
  43. define('PREG_CLASS_PUNCTUATION', '\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-\x{ff65}\x{10100}\x{10101}\x{1039f}');
  44.  
  45. /**
  46.  * Implementation of hook_help().
  47.  */
  48. function search_help($section = 'admin/help#search') {
  49.   switch ($section) {
  50.     case 'admin/modules#description':
  51.       return t('Enables site-wide keyword searching.');
  52.     case 'admin/settings/search':
  53.       return t('
  54. <p>The search engine works by maintaining an index of the words in your site\'s content. You can adjust the settings below to tweak the indexing behaviour. Note that the search requires cron to be set up correctly.</p>
  55. ');
  56.     case 'search#noresults':
  57.       return t('<p><ul>
  58. <li>Check if your spelling is correct.</li>
  59. <li>Try using wildcards: <em>walk*</em> matches <em>walker</em>, <em>walking</em>, ...</li>
  60. <li>Use longer words (words shorter than %number letters are ignored).</li>
  61. </ul></p>', array('%number' => variable_get('minimum_word_size', 3)));
  62.   }
  63. }
  64.  
  65. /**
  66.  * Implementation of hook_perm().
  67.  */
  68. function search_perm() {
  69.   return array('search content', 'administer search');
  70. }
  71.  
  72. /**
  73.  * Implementation of hook_block().
  74.  */
  75. function search_block($op = 'list', $delta = 0) {
  76.   global $user;
  77.   if ($op == 'list') {
  78.     $blocks[0]['info'] = t('Search form');
  79.     return $blocks;
  80.   }
  81.   else if ($op == 'view' && user_access('search content') && arg(0) != 'search') {
  82.     $block['content'] = search_form('', '', null, '');
  83.     $block['subject'] = t('Search');
  84.     return $block;
  85.   }
  86. }
  87.  
  88. /**
  89.  * Implementation of hook_menu().
  90.  */
  91. function search_menu($may_cache) {
  92.   $items = array();
  93.  
  94.   if ($may_cache) {
  95.     $items[] = array('path' => 'search', 'title' => t('search'),
  96.       'callback' => 'search_view',
  97.       'access' => user_access('search content'),
  98.       'type' => MENU_SUGGESTED_ITEM);
  99.  
  100.     $items[] = array('path' => 'admin/settings/search', 'title' => t('search'),
  101.       'callback' => 'search_admin',
  102.       'type' => MENU_NORMAL_ITEM,
  103.       'access' => user_access('administer site configuration'));
  104.   }
  105.   else if (arg(0) == 'search') {
  106.     // To remember the user's search keywords when switching across tabs,
  107.     // we dynamically add the keywords to the search tabs' paths.
  108.     $keys = search_get_keys();
  109.     $keys = strlen($keys) ? '/'. $keys : '';
  110.     foreach (module_list() as $name) {
  111.       if (module_hook($name, 'search') && $title = module_invoke($name, 'search', 'name')) {
  112.         $items[] = array('path' => 'search/'. $name . $keys, 'title' => $title,
  113.           'callback' => 'search_view',
  114.           'access' => user_access('search content'),
  115.           'type' => MENU_LOCAL_TASK);
  116.       }
  117.     }
  118.   }
  119.  
  120.   return $items;
  121. }
  122.  
  123.  
  124. /**
  125.  * Menu callback; displays the search module settings page.
  126.  */
  127. function search_admin() {
  128.   if ($_POST) {
  129.     // If the word length settings change, the index needs to be rebuilt.
  130.     if (variable_get('minimum_word_size', 3) != $_POST['edit']['minimum_word_size']) {
  131.       // Note: ensure logical order of messages
  132.       system_settings_save();
  133.       drupal_set_message(t('The index will be rebuilt.'));
  134.       search_wipe();
  135.     }
  136.     else {
  137.       system_settings_save();
  138.     }
  139.   }
  140.  
  141.   // Collect some stats
  142.   $remaining = 0;
  143.   $total = 0;
  144.   foreach (module_list() as $module) {
  145.     if (module_hook($module, 'search')) {
  146.       $status = module_invoke($module, 'search', 'status');
  147.       $remaining += $status['remaining'];
  148.       $total += $status['total'];
  149.     }
  150.   }
  151.   $count = format_plural($remaining, 'There is 1 item left to index.', 'There are %count items left to index.');
  152.   $percentage = ((int)min(100, 100 * ($total - $remaining) / max(1, $total))) . '%';
  153.   $status = '<p><strong>'. t('%percentage of the site has been indexed.', array('%percentage' => $percentage)) .' '. $count .'</strong></p>';
  154.   $output = form_group('Indexing status', $status);
  155.  
  156.   // Indexing throttle:
  157.   $items = drupal_map_assoc(array(10, 20, 50, 100, 200, 500));
  158.   $group = form_select(t('Items to index per cron run'), 'search_cron_limit', variable_get('search_cron_limit', 100), $items, t('The maximum amount of items that will be indexed in one cron run. Set this number lower if your cron is timing out or if PHP is running out of memory.'));
  159.   $output .= form_group(t('Indexing throttle'), $group);
  160.   // Indexing settings:
  161.   $group = '<em>'. t('<p>Changing the setting below will cause the site index to be rebuilt. The search index is not cleared but systematically updated to reflect the new settings. Searching will continue to work but new content won\'t be indexed until all existing content has been re-indexed.</p><p>The default settings should be appropriate for the majority of sites.</p>') .'</em>';
  162.   $group .= form_textfield(t('Minimum word length to index'), 'minimum_word_size', variable_get('minimum_word_size', 3), 3, 3, t('The number of characters a word has to be to be indexed. Words shorter than this will not be searchable.'));
  163.   $group .= form_textfield(t('Minimum word length to search for'), 'remove_short', variable_get('remove_short', 3), 3, 3, t('The number of characters a word has to be to be searched for, including wildcard characters.'));
  164.   $output .= form_group(t('Indexing settings'), $group);
  165.  
  166.   print theme('page', system_settings_form($output));
  167. }
  168.  
  169. /**
  170.  * Wipes a part of or the entire search index.
  171.  *
  172.  * @param $sid
  173.  *  (optional) The SID of the item to wipe. If specified, $type must be passed
  174.  *  too.
  175.  * @param $type
  176.  *  (optional) The type of item to wipe.
  177.  */
  178. function search_wipe($sid = NULL, $type = NULL) {
  179.   if ($type == NULL && $sid == NULL) {
  180.     module_invoke_all('search', 'reset');
  181.   }
  182.   else {
  183.     db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
  184.     db_query("DELETE FROM {search_index} WHERE fromsid = %d AND fromtype = '%s'", $sid, $type);
  185.   }
  186. }
  187.  
  188. /**
  189.  * Marks a word as dirty (or retrieves the list of dirty words). This is used
  190.  * during indexing (cron). Words which are dirty have outdated total counts in
  191.  * the search_total table, and need to be recounted.
  192.  */
  193. function search_dirty($word = null) {
  194.   static $dirty = array();
  195.   if ($word !== null) {
  196.     $dirty[$word] = true;
  197.   }
  198.   else {
  199.     return $dirty;
  200.   }
  201. }
  202.  
  203. /**
  204.  * Implementation of hook_cron().
  205.  *
  206.  * Fires hook_update_index() in all modules and cleans up dirty words (see
  207.  * search_dirty).
  208.  */
  209. function search_cron() {
  210.   // Update word index
  211.   foreach (module_list() as $module) {
  212.     module_invoke($module, 'update_index');
  213.   }
  214.   // Update word counts for new/changed words
  215.   foreach (search_dirty() as $word => $dummy) {
  216.     $total = db_result(db_query("SELECT SUM(score) FROM {search_index} WHERE word = '%s'", $word));
  217.     db_query("UPDATE {search_total} SET count = %d WHERE word = '%s'", $total, $word);
  218.     if (!db_affected_rows()) {
  219.       // Note: affected rows does not count matching rows that already had the right value!
  220.       $exists = db_result(db_query("SELECT COUNT(*) FROM {search_total} WHERE word = '%s'", $word));
  221.       if (!$exists) {
  222.         db_query("INSERT INTO {search_total} (word, count) VALUES ('%s', %d)", $word, $total);
  223.       }
  224.     }
  225.   }
  226.   // Find words that were deleted from search_index, but are still in
  227.   // search_total. We use a LEFT JOIN between the two tables and keep only the
  228.   // rows which fail to join.
  229.   $result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL");
  230.   while ($word = db_fetch_object($result)) {
  231.     db_query("DELETE FROM {search_total} WHERE word = '%s'", $word->realword);
  232.   }
  233. }
  234.  
  235. /**
  236.  * Splits a string into component words according to indexing rules.
  237.  */
  238. function search_keywords_split($text) {
  239.   static $last = null;
  240.   static $lastsplit = null;
  241.  
  242.   if ($last == $text) {
  243.     return $lastsplit;
  244.   }
  245.  
  246.   // Decode entities to UTF-8
  247.   $text = decode_entities($text);
  248.  
  249.   // Call an external processor for word handling.
  250.   search_preprocess($text);
  251.  
  252.   // To improve searching for numerical data such as dates, IP addresses
  253.   // or version numbers, we consider a group of numerical characters
  254.   // separated only by punctuation characters to be one piece.
  255.   // This also means that searching for e.g. '20/03/1984' also returns
  256.   // results with '20-03-1984' in them.
  257.   // Readable regexp: ([number]+)[punctuation]+(?=[number])
  258.   $text = preg_replace('/(['. PREG_CLASS_NUMBERS .']+)['. PREG_CLASS_PUNCTUATION .']+(?=['. PREG_CLASS_NUMBERS .'])/u', '\1', $text);
  259.  
  260.   // The dot, underscore and dash are simply removed. This allows meaningful
  261.   // search behaviour with acronyms and URLs.
  262.   $text = preg_replace('/[._-]+/', '', $text);
  263.  
  264.   // With the exception of the rules above, we consider all punctuation,
  265.   // marks, spacers, etc, to be a word boundary.
  266.   $text = preg_replace('/['. PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ', $text);
  267.  
  268.   // Process words
  269.   $words = explode(' ', $text);
  270.   array_walk($words, '_search_keywords_truncate');
  271.  
  272.   // Save last keyword result
  273.   $last = $text;
  274.   $lastsplit = $words;
  275.  
  276.   return $words;
  277. }
  278.  
  279. /**
  280.  * Helper function for array_walk in search_keywords_split.
  281.  */
  282. function _search_keywords_truncate(&$text) {
  283.   $text = truncate_utf8($text, 50);
  284. }
  285.  
  286. /**
  287.  * Loosens up a set of search keywords by adding wildcards, if possible.
  288.  *
  289.  * @param $text
  290.  *   The keywords as entered by the user.
  291.  * @return
  292.  *   If more wildcards can be added, the adjusted keywords are returned.
  293.  *   If the query is already as loose as possible, NULL is returned.
  294.  */
  295. function search_keywords_variation($text) {
  296.   $text = trim($text);
  297.   $new = preg_replace('/\*+/', '*', '*'. implode('* *', explode(' ', trim($text))) .'*');
  298.   return ($new != $text) ? $new : NULL;
  299. }
  300.  
  301. /**
  302.  * Invokes hook_search_preprocess() in modules.
  303.  */
  304. function search_preprocess(&$text) {
  305.   foreach (module_implements('search_preprocess') as $module) {
  306.     $text = module_invoke($module, 'search_preprocess', $text);
  307.   }
  308. }
  309.  
  310.  
  311. /**
  312.  * Update the full-text search index for a particular item.
  313.  *
  314.  * @param $sid
  315.  *   A number identifying this particular item (e.g. node id).
  316.  *
  317.  * @param $type
  318.  *   A string defining this type of item (e.g. 'node')
  319.  *
  320.  * @param $text
  321.  *   The content of this item. Must be a piece of HTML text.
  322.  *
  323.  * @ingroup search
  324.  */
  325. function search_index($sid, $type, $text) {
  326.   $minimum_word_size = variable_get('minimum_word_size', 3);
  327.  
  328.   global $base_url;
  329.   $node_regexp = '!href=[\'"]?(?:'. preg_quote($base_url) .'/)?(?:\?q=)?([^\'">]+)[\'">]!i';
  330.  
  331.   // Multipliers for scores of words inside certain HTML tags.
  332.   // Note: 'a' must be included for link ranking to work.
  333.   $tags = array('h1' => 21,
  334.                 'h2' => 18,
  335.                 'h3' => 15,
  336.                 'h4' => 12,
  337.                 'h5' => 9,
  338.                 'h6' => 6,
  339.                 'u' => 5,
  340.                 'b' => 5,
  341.                 'strong' => 5,
  342.                 'em' => 5,
  343.                 'a' => 10);
  344.  
  345.   // Strip off all ignored tags to speed up processing, but insert space before/after
  346.   // them to keep word boundaries.
  347.   $text = str_replace(array('<', '>'), array(' <', '> '), $text);
  348.   $text = strip_tags($text, '<'. implode('><', array_keys($tags)) .'>');
  349.  
  350.   // Split HTML tags from plain text.
  351.   $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  352.   // Note: PHP ensures the array consists of alternating delimiters and literals
  353.   // and begins and ends with a literal (inserting $null as required).
  354.  
  355.   $tag = false; // Odd/even counter. Tag or no tag.
  356.   $link = false; // State variable for link analyser
  357.   $score = 1; // Starting score per word
  358.  
  359.   $results = array(0 => array());
  360.  
  361.   foreach ($split as $value) {
  362.     if ($tag) {
  363.       // Increase or decrease score per word based on tag
  364.       list($tagname) = explode(' ', $value, 2);
  365.       $tagname = strtolower($tagname);
  366.       if ($tagname{0} == '/') {
  367.         $score -= $tags[substr($tagname, 1)];
  368.         if ($score < 1) { // possible due to bad HTML
  369.           $score = 1;
  370.         }
  371.         if ($tagname == '/a') {
  372.           $link = false;
  373.         }
  374.       }
  375.       else {
  376.         if ($tagname == 'a') {
  377.           // Check if link points to a node on this site
  378.           if (preg_match($node_regexp, $value, $match)) {
  379.             $path = drupal_get_normal_path($match[1]);
  380.             if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
  381.               $linknid = $match[1];
  382.               if ($linknid > 0) {
  383.                 $link = true;
  384.               }
  385.             }
  386.           }
  387.         }
  388.         $score += $tags[$tagname];
  389.       }
  390.     }
  391.     else {
  392.       // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
  393.       if ($value != '') {
  394.         $words = search_keywords_split($value);
  395.         foreach ($words as $word) {
  396.           // Check wordlength
  397.           if (string_length($word) >= $minimum_word_size) {
  398.             // Note: strtolower can be used because the value is only used internally.
  399.             $word = strtolower($word);
  400.             if ($link) {
  401.               if (!isset($results[$linknid])) {
  402.                 $results[$linknid] = array();
  403.               }
  404.               $results[$linknid][$word] += $score;
  405.             }
  406.             else {
  407.               $results[0][$word] += $score;
  408.             }
  409.           }
  410.         }
  411.       }
  412.     }
  413.     $tag = !$tag;
  414.   }
  415.  
  416.   search_wipe($sid, $type);
  417.  
  418.   // Insert results into search index
  419.   foreach ($results[0] as $word => $score) {
  420.     db_query("INSERT INTO {search_index} (word, sid, type, score) VALUES ('%s', %d, '%s', %d)", $word, $sid, $type, $score);
  421.     search_dirty($word);
  422.   }
  423.   unset($results[0]);
  424.  
  425.   // Now insert links to nodes
  426.   foreach ($results as $nid => $words) {
  427.     foreach ($words as $word => $score) {
  428.       db_query("INSERT INTO {search_index} (word, sid, type, fromsid, fromtype, score) VALUES ('%s', %d, '%s', %d, '%s', %d)", $word, $nid, 'node', $sid, $type, $score);
  429.       search_dirty($word);
  430.     }
  431.   }
  432. }
  433.  
  434. /**
  435.  * Do a query on the full-text search index for a word or words.
  436.  *
  437.  * This function is normally only called by each module that support the
  438.  * indexed search (and thus, implements hook_update_index()).
  439.  *
  440.  * The final query is an SQL select on the search_index table. As a guide for
  441.  * writing the optional extra SQL fragments (see below), use this query:
  442.  *
  443.  * SELECT i.type, i.sid, i.word, SUM(i.score/t.count) AS score
  444.  * FROM {search_index} i
  445.  * $join INNER JOIN {search_total} t ON i.word = t.word
  446.  * WHERE $where AND (i.word = '...' OR ...)
  447.  * GROUP BY i.type, i.sid
  448.  * ORDER BY score DESC";
  449.  *
  450.  * @param $keywords
  451.  *   A search string as entered by the user.
  452.  *
  453.  * @param $type
  454.  *   A string identifying the calling module.
  455.  *
  456.  * @param $join
  457.  *   (optional) A string to be inserted into the JOIN part of the SQL query.
  458.  *   For example "INNER JOIN {node} n ON n.nid = i.sid".
  459.  *
  460.  * @param $where
  461.  *   (optional) A string to be inserted into the WHERE part of the SQL query.
  462.  *   For example "(n.status > 0)".
  463.  *
  464.  * @param $variation
  465.  *   Used internally. Must not be specified.
  466.  *
  467.  * @return
  468.  *   An array of SIDs for the search results.
  469.  *
  470.  * @ingroup search
  471.  */
  472. function do_search($keywords, $type, $join = '', $where = '1', $variation = true) {
  473.   // Note, we replace the wildcards with U+FFFD (Replacement character) to pass
  474.   // through the keyword extractor. Multiple wildcards are collapsed into one.
  475.   $keys = preg_replace('!\*+!', '∩┐╜', $keywords);
  476.  
  477.   // Split into words
  478.   $keys = search_keywords_split($keys);
  479.  
  480.   $words = array();
  481.   $arguments = array();
  482.   $refused = array();
  483.   // Build WHERE clause
  484.   foreach ($keys as $word) {
  485.     if (string_length($word) < variable_get('remove_short', 3)) {
  486.       if ($word != '') {
  487.         $refused[] = str_replace('∩┐╜', '*', $word);
  488.       }
  489.       continue;
  490.     }
  491.     if (strpos($word, '∩┐╜') !== false) {
  492.       // Note: strtolower can be used because the value is only used internally.
  493.       $words[] = "i.word LIKE '%s'";
  494.       $arguments[] = str_replace('∩┐╜', '%', strtolower($word));
  495.     }
  496.     else {
  497.       $words[] = "i.word = '%s'";
  498.       $arguments[] = strtolower($word);
  499.     }
  500.   }
  501.   // Tell the user which words were excluded
  502.   if (count($refused) && $variation) {
  503.     $message = format_plural(count($refused),
  504.                              'The word %words was not included because it is too short.',
  505.                              'The words %words were not included because they were too short.');
  506.     drupal_set_message(strtr($message, array('%words' => theme('placeholder', implode(', ', $refused)))));
  507.   }
  508.  
  509.   if (count($words) == 0) {
  510.     return array();
  511.   }
  512.   $conditions = $where .' AND ('. implode(' OR ', $words) .')';
  513.  
  514.   // Get result count (for pager)
  515.   $count = db_num_rows(db_query("SELECT DISTINCT i.sid, i.type FROM {search_index} i $join WHERE $conditions", $arguments));
  516.   if ($count == 0) {
  517.     // Try out a looser search query if nothing was found.
  518.     if ($variation && $loose = search_keywords_variation($keywords)) {
  519.       return do_search($loose, $type, $join, $where, false);
  520.     }
  521.     else {
  522.       return array();
  523.     }
  524.   }
  525.   $count_query = "SELECT $count";
  526.  
  527.   // Do pager query
  528.   $query = "SELECT i.type, i.sid, SUM(i.score/t.count) AS score FROM {search_index} i $join INNER JOIN {search_total} t ON i.word = t.word WHERE $conditions GROUP BY i.type, i.sid ORDER BY score DESC";
  529.   $result = pager_query($query, 15, 0, $count_query, $arguments);
  530.  
  531.   $results = array();
  532.   while ($item = db_fetch_object($result)) {
  533.     $results[] = $item->sid;
  534.   }
  535.  
  536.   return $results;
  537. }
  538.  
  539. /**
  540.  * Helper function for grabbing search keys.
  541.  */
  542. function search_get_keys() {
  543.   // Extract keys as remainder of path
  544.   // Note: support old GET format of searches for existing links.
  545.   $path = explode('/', $_GET['q'], 3);
  546.   return count($path) == 3 ? $path[2] : $_REQUEST['keys'];
  547. }
  548.  
  549. /**
  550.  * Menu callback; presents the search form and/or search results.
  551.  */
  552. function search_view() {
  553.   $type = arg(1);
  554.  
  555.   // Search form submits with POST but redirects to GET. This way we can keep
  556.   // the search query URL clean as a whistle:
  557.   // search/type/keyword+keyword
  558.   if ($_POST['edit']['keys']) {
  559.     if ($type == '') {
  560.       $type = 'node';
  561.     }
  562.     drupal_goto('search/'. urlencode($type) .'/'. urlencode($_POST['edit']['keys']));
  563.   }
  564.   else if ($type == '') {
  565.     // Note: search/node can not be a default tab because it would take on the
  566.     // path of its parent (search). It would prevent remembering keywords when
  567.     // switching tabs. This is why we drupal_goto to it from the parent instead.
  568.     drupal_goto('search/node');
  569.   }
  570.   $keys = search_get_keys();
  571.  
  572.   if (user_access('search content')) {
  573.     // Only perform search if there is non-whitespace search term:
  574.     if (trim($keys)) {
  575.       // Log the search keys:
  576.       watchdog('search',
  577.         t('Search: %keys (%type).', array('%keys' => theme('placeholder', $keys), '%type' => module_invoke($type, 'search', 'name'))),
  578.         WATCHDOG_NOTICE,
  579.         l(t('results'), 'search/'. urlencode($type) .'/'. urlencode($keys))
  580.         );
  581.  
  582.       // Collect the search results:
  583.       $results = search_data($keys, $type);
  584.  
  585.       if ($results) {
  586.         $results = theme('box', t('Search results'), $results);
  587.       }
  588.       else {
  589.         $results = theme('box', t('Your search yielded no results'), search_help('search#noresults'));
  590.       }
  591.     }
  592.     else if (isset($_POST['edit'])) {
  593.       form_set_error('keys', t('Please enter some keywords.'));
  594.     }
  595.  
  596.     // Construct the search form.
  597.     // Note, we do this last because of the form_set_error() above.
  598.     $output = search_form(NULL, $keys, $type);
  599.  
  600.     $output .= $results;
  601.  
  602.     print theme('page', $output);
  603.   }
  604.   else {
  605.     drupal_access_denied();
  606.   }
  607. }
  608.  
  609. /**
  610.  * @defgroup search Search interface
  611.  * @{
  612.  * The Drupal search interface manages a global search mechanism.
  613.  *
  614.  * Modules may plug into this system to provide searches of different types of
  615.  * data. Most of the system is handled by search.module, so this must be enabled
  616.  * for all of the search features to work.
  617.  *
  618.  * There are three ways to interact with the search system:
  619.  * - Specifically for searching nodes, you can implement nodeapi('update index')
  620.  *   and nodeapi('search result'). However, note that the search system already
  621.  *   indexes all visible output of a node, i.e. everything displayed normally
  622.  *   by hook_view() and hook_nodeapi('view'). This is usually sufficient.
  623.  *   You should only use this mechanism if you want additional, non-visible data
  624.  *   to be indexed.
  625.  * - Implement hook_search(). This will create a search tab for your module on
  626.  *   the /search page with a simple keyword search form. You may optionally
  627.  *   implement hook_search_item() to customize the display of your results.
  628.  * - Implement hook_update_index(). This allows your module to use Drupal's
  629.  *   HTML indexing mechanism for searching full text efficiently.
  630.  *
  631.  * If your module needs to provide a more complicated search form, then you need
  632.  * to implement it yourself without hook_search(). In that case, you should
  633.  * define it as a local task (tab) under the /search page (e.g. /search/mymodule)
  634.  * so that users can easily find it.
  635.  */
  636.  
  637. /**
  638.  * Render a search form.
  639.  *
  640.  * @param $action
  641.  *   Form action. Defaults to "search".
  642.  * @param $keys
  643.  *   The search string entered by the user, containing keywords for the search.
  644.  * @param $type
  645.  *   The type of search to render the node for. Must be the name of module
  646.  *   which implements hook_search(). Defaults to 'node'.
  647.  * @param $prompt
  648.  *   A piece of text to put before the form (e.g. "Enter your keywords")
  649.  * @return
  650.  *   An HTML string containing the search form.
  651.  */
  652. function search_form($action = '', $keys = '', $type = null, $prompt = null) {
  653.   $edit = $_POST['edit'];
  654.  
  655.   if (!$action) {
  656.     $action = url('search/'. $type);
  657.   }
  658.   if (!$type) {
  659.     $type = 'node';
  660.   }
  661.   if (is_null($prompt)) {
  662.     $prompt = t('Enter your keywords');
  663.   }
  664.  
  665.   $output = ' <div class="search-form">';
  666.   $box = '<div class="container-inline">';
  667.   $box .= form_textfield('', 'keys', $keys, $prompt ? 40 : 20, 255);
  668.   $box .= form_submit(t('Search'));
  669.   $box .= '</div>';
  670.   $output .= form_item($prompt, $box);
  671.   $output .= '</div>';
  672.  
  673.   return form($output, 'post', $action);
  674. }
  675.  
  676. /**
  677.  * Perform a standard search on the given keys, and return the formatted results.
  678.  */
  679. function search_data($keys = NULL, $type = 'node') {
  680.   $output = '';
  681.  
  682.   if (isset($keys)) {
  683.     if (module_hook($type, 'search')) {
  684.       $results = module_invoke($type, 'search', 'search', $keys);
  685.       if (is_array($results) && count($results)) {
  686.         $output .= '<dl class="search-results">';
  687.         foreach ($results as $entry) {
  688.           $output .= theme('search_item', $entry, $type);
  689.         }
  690.         $output .= '</dl>';
  691.         $output .= theme('pager', NULL, 15, 0);
  692.       }
  693.     }
  694.   }
  695.  
  696.   return $output;
  697. }
  698.  
  699. /**
  700.  * Returns snippets from a piece of text, with certain keywords highlighted.
  701.  * Used for formatting search results.
  702.  *
  703.  * @param $keys
  704.  *   A string containing keywords. They are split into words using the same
  705.  *   rules as search indexing.
  706.  *
  707.  * @param $text
  708.  *   The text to extract fragments from.
  709.  *
  710.  * @return
  711.  *   A string containing HTML for the excerpt.
  712.  */
  713. function search_excerpt($keys, $text) {
  714.   $keys = search_keywords_split($keys);
  715.   $text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
  716.   array_walk($keys, '_search_excerpt_replace');
  717.   $workkeys = $keys;
  718.  
  719.   // Extract a fragment per keyword for at most 4 keywords.
  720.   // First we collect ranges of text around each keyword, starting/ending
  721.   // at spaces.
  722.   // If the sum of all fragments is too short, we look for second occurrences.
  723.   $ranges = array();
  724.   $included = array();
  725.   $length = 0;
  726.   while ($length < 256 && count($workkeys)) {
  727.     foreach ($workkeys as $k => $key) {
  728.       if (strlen($key) == 0) {
  729.         unset($workkeys[$k]);
  730.         continue;
  731.       }
  732.       if ($length >= 256) {
  733.         break;
  734.       }
  735.       // Remember occurrence of key so we can skip over it if more occurrences
  736.       // are desired.
  737.       if (!isset($included[$key])) {
  738.         $included[$key] = 0;
  739.       }
  740.       // Locate a keyword (position $p), then locate a space in front (position
  741.       // $q) and behind it (position $s)
  742.       if (preg_match('/\b'. $key .'\b/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
  743.         $p = $match[0][1];
  744.         if (($q = strpos($text, ' ', max(0, $p - 60))) !== false) {
  745.           $end = substr($text, $p, 80);
  746.           if (($s = strrpos($end, ' ')) !== false) {
  747.             $ranges[$q] = $p + $s;
  748.             $length += $p + $s - $q;
  749.             $included[$key] = $p + 1;
  750.           }
  751.           else {
  752.             unset($workkeys[$k]);
  753.           }
  754.         }
  755.         else {
  756.           unset($workkeys[$k]);
  757.         }
  758.       }
  759.       else {
  760.         unset($workkeys[$k]);
  761.       }
  762.     }
  763.   }
  764.  
  765.   // If we didn't find anything, return the beginning.
  766.   if (count($ranges) == 0) {
  767.     return truncate_utf8($text, 256) . ' ...';
  768.   }
  769.  
  770.   // Sort the text ranges by starting position.
  771.   ksort($ranges);
  772.  
  773.   // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
  774.   $newranges = array();
  775.   foreach ($ranges as $from2 => $to2) {
  776.     if (!isset($from1)) {
  777.       $from1 = $from2;
  778.       $to1 = $to2;
  779.       continue;
  780.     }
  781.     if ($from2 <= $to1) {
  782.       $to1 = max($to1, $to2);
  783.     }
  784.     else {
  785.       $newranges[$from1] = $to1;
  786.       $from1 = $from2;
  787.       $to1 = $to2;
  788.     }
  789.   }
  790.   $newranges[$from1] = $to1;
  791.  
  792.   // Fetch text
  793.   $out = array();
  794.   foreach ($newranges as $from => $to) {
  795.     $out[] = substr($text, $from, $to - $from);
  796.   }
  797.   $text = (isset($newranges[0]) ? '' : '... '). implode(' ... ', $out) .' ...';
  798.  
  799.   // Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  800.   $text = preg_replace('/\b('. implode('|', $keys) .')\b/iu', '<strong>\0</strong>', $text);
  801.   return $text;
  802. }
  803.  
  804. /**
  805.  * @} End of "defgroup search".
  806.  */
  807.  
  808. /**
  809.  * Helper function for array_walk in search_except.
  810.  */
  811. function _search_excerpt_replace(&$text) {
  812.   $text = preg_quote($text, '/');
  813. }
  814.  
  815. /**
  816.  * Format a single result entry of a search query.
  817.  *
  818.  * Modules may implement hook_search_item() in order to override this default
  819.  * function to display search results.
  820.  *
  821.  * @param $item
  822.  *   A single search result as returned by hook_search(). The result should be
  823.  *   an array with keys "link", "title", "type", "user", "date", and "snippet".
  824.  *   Optionally, "extra" can be an array of extra info to show along with the
  825.  *   result.
  826.  * @param $type
  827.  *   The type of item found, such as "user" or "node".
  828.  *
  829.  * @ingroup themeable
  830.  */
  831. function theme_search_item($item, $type) {
  832.   if (module_hook($type, 'search_item')) {
  833.     $output = module_invoke($type, 'search_item', $item);
  834.   }
  835.   else {
  836.     $output = ' <dt class="title"><a href="'. check_url($item['link']) .'">'. check_plain($item['title']) .'</a></dt>';
  837.     $info = array();
  838.     if ($item['type']) {
  839.       $info[] = $item['type'];
  840.     }
  841.     if ($item['user']) {
  842.       $info[] = $item['user'];
  843.     }
  844.     if ($item['date']) {
  845.       $info[] = format_date($item['date'], 'small');
  846.     }
  847.     if (is_array($item['extra'])) {
  848.       $info = array_merge($info, $item['extra']);
  849.     }
  850.     $output .= ' <dd>'. ($item['snippet'] ? '<p>'. $item['snippet'] . '</p>' : '') . '<p class="search-info">' . implode(' - ', $info) .'</p></dd>';
  851.   }
  852.  
  853.   return $output;
  854. }
  855.  
  856.  
  857. ?>
  858.